package org.example;

import com.sun.security.auth.UserPrincipal;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class BatchWordCount<T>{
    public static void main(String[] args) throws Exception {

        // 创建执行环境
        ExecutionEnvironment executionEnvironment = ExecutionEnvironment.getExecutionEnvironment();

        DataSource<String> source = executionEnvironment.readTextFile("/Users/fengliulin/IdeaProjects/hadoop-learn/data-test/words.txt");

        // 讲每一行数据拆分
        FlatMapOperator<String, Tuple2<String, Long>> flatMapOperator = source.flatMap((String line, Collector<Tuple2<String, Long>> out) -> {
            String[] words = line.split(" ");
            for (String s : words) {
                out.collect(Tuple2.of(s, 1L));
            }
        }).returns(Types.TUPLE(Types.STRING, Types.LONG));

        // 按照word进行分组
        UnsortedGrouping<Tuple2<String, Long>> groupBy = flatMapOperator.groupBy(0);

        // 分组内进行聚合统计
        AggregateOperator<Tuple2<String, Long>> sum = groupBy.sum(1);
        sum.print();

        System.out.println("Hello world!");
    }

}